﻿using System;
using System.IO;
using System.Messaging;
using System.Collections.Generic;

namespace NHTrace
{
  /// <summary>
  /// Based on MsmqReceiver class from log2console project: http://log2console.codeplex.com/ - Copyright (c) 2007, Rémy Baudet
  /// </summary>
  public class MsmqReceiver : IReceiver
  {
    public MsmqReceiver(Logger logger, Dictionary<string, string> receiverParameters)
    {
      _queueName = (string)receiverParameters["queueName"];

      _logger = logger;
    }

    private MessageQueue _queue;
    private Logger _logger;
    private string _queueName = string.Empty;// = @".\private$\nhtrace";

    public void Initialize()
    {
      if (!MessageQueue.Exists(_queueName))
        MessageQueue.Create(_queueName, false);

      start();
    }

    private void start()
    {
      _queue = new MessageQueue(_queueName);

      _queue.ReceiveCompleted += delegate(Object source, ReceiveCompletedEventArgs asyncResult)
      {
        try
        {
          // End the asynchronous receive operation.
          Message m = ((MessageQueue)source).EndReceive(asyncResult.AsyncResult);

          string loggingEvent = System.Text.Encoding.ASCII.GetString(((MemoryStream)m.BodyStream).ToArray());
          LogMessage logMsg = ReceiverUtils.ParseLog4JXmlLogEvent(loggingEvent, "MSMQLogger");
          logMsg.Id = long.Parse(m.Id.Substring(37));// sample queue Id: {807457FF-3BF0-48CC-89C1-68C30F7D3749}\4836

          _logger.LogEvents(new List<LogMessage>() { logMsg });

          ((MessageQueue)source).BeginReceive();
        }
        catch (MessageQueueException /*mqEx*/)
        {
          //ExceptionHandler.HandleException(mqEx);
        }
      };

      _queue.BeginReceive();
    }

    public void Terminate()
    {
      if (_queue != null)
      {
        _queue.Close();
      }
    }
  }

}
